package com.luhaoran.hrm.service.Impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luhaoran.hrm.entity.User;
import com.luhaoran.hrm.exception.MyJsonValidationException;
import com.luhaoran.hrm.mapper.IUserMapper;
import com.luhaoran.hrm.service.IUserService;
import com.luhaoran.hrm.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service     //通过添加注解，就将该类放置到Spring容器里，将由Spring容器来帮我们管理，也就是将该类的控制权由开发者反转给Spring容器
@Slf4j
public class UserServiceImpl extends ServiceImpl<IUserMapper, User> implements IUserService {

    @Override
    public JSONObject login(User user){

        //构造一个User类的条件构造器
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",user.getUsername())
                        .eq("password",user.getPassword());

        //通过使用getOne方法，执行SQL语句，将查询结果重新赋给user
        user = getOne(userQueryWrapper);
        if(user == null){
//            说明在数据库中没有查找匹配的数据
            throw new MyJsonValidationException("用户名或密码错误");
//            只要执行了上面的代码那，此处的程序就会被中断执行，不会再执行后面的代码
        }
        JSONObject result = new JSONObject();
        result.put("id",user.getId());
        result.put("username",user.getUsername());
        result.put("password",user.getPassword());
        Date issuedTime = new Date();    //当前签发时间
        Date expiresTime = new Date(issuedTime.getTime() + 1000*60*60);
        String token = TokenUtils.generate(user.getId(),issuedTime,expiresTime);
        log.info("token"+token);
        result.put("token",token);
        return result;
    }

    @Override
    public List<User> getList() {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.gt("id",1);
        List<User> users = list(userQueryWrapper);
        return users;
    }

    @Override
    public Integer saveUser(User user) {
//        先到数据库查询要插入的user数据是否存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",user.getUsername());
        userQueryWrapper.ne("id",user.getId());
        if(count(userQueryWrapper) > 0){
//            如果查询出来的结果大于0，那就说明username已存在于数据库
            throw new MyJsonValidationException("用户名已存在");
        }
        user.setState(1);
        saveOrUpdate(user);
        return user.getId();
    }

    @Override
    public void changePwd(Integer id, String password) {
        User user = new User();
        user.setId(id);
        user.setPassword(password);
        updateById(user);

    }

    @Override
    public void removeUser(Integer id) {
        if (!removeById(id)){
            throw new MyJsonValidationException("删除失败,请检查id");
        }
    }

}
